﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using EPubLib;

namespace UI
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();

            //Set up the dataset
            this.Chapters = new DataTable();
            this.Chapters.Columns.Add("Number");
            this.Chapters.Columns.Add("Filename");
            this.Chapters.Columns.Add("Path");
            //And bind it
            this.dgvChapters.DataSource = this.Chapters;


        }

        private DataTable Chapters;

        private void btnAdd_Click(object sender, EventArgs e)
        {
            OpenFileDialog file = new OpenFileDialog();
            file.Filter = "HTML Documents (*.html;*.xhtml)|*.html;*.xhtml|All Files (*.*)|*.*";
            file.Multiselect = true;

            if (DialogResult.OK == file.ShowDialog())
            {
                foreach (string path in file.FileNames)
                {
                    AddChapter(new FileInfo(path));
                }
            }
        }

        private void AddChapter(FileInfo file)
        {
            this.dgvChapters.SuspendLayout();
            DataRow newChapter = this.Chapters.NewRow();
            newChapter["Number"] = this.Chapters.Rows.Count + 1;
            newChapter["Filename"] = file.Name;
            newChapter["Path"] = file.Directory.FullName;
            this.Chapters.Rows.Add(newChapter);
            this.dgvChapters.ResumeLayout();
        }

        /// <summary>
        /// Removes the highlighted rows
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnRemove_Click(object sender, EventArgs e)
        {
            this.dgvChapters.SuspendLayout();
            //Delete the row
            foreach (DataGridViewRow row in this.dgvChapters.SelectedRows)
            {
                ((System.Data.DataRowView)row.DataBoundItem).Row.Delete();
            }

            RenumberChapters();
            this.dgvChapters.ResumeLayout();
        }

        /// <summary>
        /// Iterates over the datatable and numbers the chapters sequentially
        /// </summary>
        private void RenumberChapters()
        {
            //And renumber the chapter
            int i = 1;
            foreach (DataRow row in this.Chapters.Rows)
            {
                row["Number"] = i;
                i++;
            }
        }

        private void btnUp_Click(object sender, EventArgs e)
        {
            MoveRow(true);
        }

        /// <summary>
        /// Moves the selected rows up or down
        /// </summary>
        /// <param name="up">True to move up (physically)--that is, to move the chapter number closer to 1</param>
        private void MoveRow(bool up)
        {
            this.dgvChapters.SuspendLayout();

            //Set the direction of movement
            int dir = up ? -1 : 1;

            //Move the row up
            foreach (DataGridViewRow dgvRow in this.dgvChapters.SelectedRows)
            {
                DataRow oldRow = ((System.Data.DataRowView)dgvRow.DataBoundItem).Row;
                int i = this.Chapters.Rows.IndexOf(oldRow);
                
                //Bounds checking for moving up or down
                if ((up && i > 0)
                    || (!up && i < this.Chapters.Rows.Count - 1))
                {
                    string filename = this.Chapters.Rows[i]["Filename"] as string;
                    string path = this.Chapters.Rows[i]["Path"] as string;

                    this.Chapters.Rows[i]["Filename"] = this.Chapters.Rows[i + dir]["Filename"];
                    this.Chapters.Rows[i]["Path"] = this.Chapters.Rows[i + dir]["Path"];

                    this.Chapters.Rows[i + dir]["Filename"] = filename;
                    this.Chapters.Rows[i + dir]["Path"] = path;
                }
            }

            this.dgvChapters.ResumeLayout();
        }

        private void btnDown_Click(object sender, EventArgs e)
        {
            MoveRow(false);
        }

        private void dgvChapters_SelectionChanged(object sender, EventArgs e)
        {
            foreach (DataGridViewRow row in this.dgvChapters.SelectedRows)
            {
                DataRow oldRow = ((System.Data.DataRowView)row.DataBoundItem).Row;
                this.webBrowserPreview.ScriptErrorsSuppressed = true;
                //this.webBrowserPreview.ScrollBarsEnabled = true;
                this.webBrowserPreview.Navigate(GetFullPath(oldRow));

                
                //Only show the first one
                break;
            }
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            Book book = new Book();
            foreach (DataRow row in this.Chapters.Rows)
            {
                Chapter chapter = new Chapter();
                chapter.Number = Int32.Parse((string)row["Number"]);
                chapter.Title = (string)row["Filename"];
                chapter.Content = (new StreamReader(File.OpenRead(GetFullPath(row)))).ReadToEnd();
                book.FileItems.Add(chapter);
            }

            SaveFileDialog save = new SaveFileDialog();
            save.Filter = "ePub Files (*.epub)|*.epub|All Files (*.*)|*.*";
            if (save.ShowDialog() == DialogResult.OK)
            {
                book.Save(save.FileName);
            }
        }

        private string GetFullPath(DataRow row)
        {
            return row["Path"].ToString() + "\\" + row["Filename"].ToString();
        }
    }
}
